<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="古代英雄战争模拟 - 选择历史英雄组建阵容，体验AI战斗分析">
    <title>古代英雄战争模拟</title>
    <!-- Tailwind CSS -->
    <script src="../js/tailwind-3.4.17.js"></script>
    <script src="../js/data.js"></script>
    <!-- Font Awesome -->
    <link href="../css/font-awesome.min.css" rel="stylesheet">


    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#ff4d4f',
                        secondary: '#1890ff',
                        neutral: '#595959',
                        success: '#52c41a',
                        warning: '#faad14',
                        info: '#1890ff',
                        purple: '#722ed1'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>

    <style>
        /* 全局样式 */
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background-color: #f0f2f5;
        }

        /* 英雄卡片样式 */
        .hero-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 10px;
            background: white;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-align: center;
            position: relative;
            overflow: hidden;
            height: 180px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .hero-card:hover {
            transform: translateY(-4px) scale(1.02);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12), 0 3px 6px rgba(0, 0, 0, 0.08);
            border-color: #1890ff;
        }

        .hero-card.selected {
            border-color: #1890ff;
            background-color: #e6f7ff;
        }

        .hero-card:hover .add-buttons {
            opacity: 1;
            transform: translateY(0);
        }

        .hero-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            margin: 0 auto 8px;
            object-fit: cover;
            transition: transform 0.3s ease;
            border: 2px solid transparent;
        }

        .hero-card:hover .hero-avatar {
            transform: scale(1.05);
            border-color: #1890ff;
        }

        .hero-name {
            font-weight: 600;
            font-size: 16px;
            margin-bottom: 4px;
            color: #333;
        }

        .hero-title {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .hero-tag {
            display: inline-block;
            font-size: 11px;
            padding: 2px 6px;
            border-radius: 4px;
            margin: 0 2px 2px 2px;
            transition: all 0.2s ease;
        }

        .tag-era {
            background: #e6f7ff;
            color: #1890ff;
        }

        .tag-type {
            background: #f0f9eb;
            color: #52c41a;
        }

        /* 加入阵营按钮 */
        .add-buttons {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            display: flex;
            background: rgba(255, 255, 255, 0.95);
            padding: 4px 0;
            opacity: 0;
            transform: translateY(100%);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 10;
        }

        .add-btn {
            flex: 1;
            margin: 0 3px;
            padding: 4px 0;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            border: none;
            transition: all 0.2s ease;
        }

        .add-red {
            background: #ff4d4f;
            color: white;
        }

        .add-red:hover {
            background: #ff7875;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(255, 77, 79, 0.2);
        }

        .add-blue {
            background: #1890ff;
            color: white;
        }

        .add-blue:hover {
            background: #40a9ff;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
        }

        /* 布局网格 */
        .hero-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .formation-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 15px;
        }

        /* 阵容槽位 */
        .formation-slot {
            border: 2px dashed #ddd;
            border-radius: 6px;
            padding: 6px;
            margin: 5px;
            min-height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #fafafa;
            position: relative;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .formation-slot:hover {
            border-color: #1890ff;
            background: #f0f8ff;
        }

        .formation-slot.bg-red-50:hover {
            border-color: #ff4d4f;
            background: #fff1f0;
        }

        .formation-slot.bg-blue-50:hover {
            border-color: #1890ff;
            background: #f0f8ff;
        }

        .slot-occupied {
            background: #fff;
            border-style: solid;
            border-color: #d9d9d9;
            padding: 5px;
            cursor: default;
        }

        .slot-occupied:hover {
            border-color: #1890ff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        /* 移除按钮 */
        .remove-hero {
            position: absolute;
            top: -10px;
            right: -10px;
            background: #ff4d4f;
            color: white;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            cursor: pointer;
            border: none;
            padding: 0;
            line-height: 1;
            z-index: 5;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
        }

        .remove-hero:hover {
            background: #ff7875;
            transform: scale(1.1);
        }

        /* 槽位内容 */
        .slot-content {
            text-align: center;
            width: 100%;
            position: relative;
        }

        /* 分类名称样式 */
        .slot-category {
            position: absolute;
            top: -18px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #138a25;
            color: white;
            padding: 4px 10px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            z-index: 10;
            white-space: nowrap;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .slot-category:hover {
            background-color: #055014;
            transform: translateX(-50%) scale(1.05);
        }

        /* 英雄列表弹出框样式 - 普通列表 */
        .hero-list-popup {
            position: absolute;
            background: #ffffff;
            border: 1px solid #d9d9d9;
            border-radius: 6px;
            padding: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
            z-index: 400;
            display: none;
            min-width: 130px;
            max-height: 360px;
            overflow-y: auto;
        }

        .hero-list-popup.show {
            display: block;
        }

        .hero-tooltip {
            position: absolute;
            background: rgba(28, 28, 30, 0.92);
            color: #fff;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            line-height: 1.5;
            box-shadow: 0 6px 18px rgba(0, 0, 0, 0.3);
            max-width: 260px;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.12s ease;
            z-index: 1000;
        }

        .hero-tooltip.show {
            opacity: 1;
        }

        .hero-tooltip-name {
            font-weight: 600;
            margin-bottom: 4px;
        }

        .hero-tooltip-stats {
            opacity: 0.85;
            margin-bottom: 4px;
        }

        .hero-tooltip-specialty {
            opacity: 0.75;
        }

        .hero-tooltip-biography {
            opacity: 0.75;
        }

        .hero-tooltip-avatar {
            margin-top: 4px;
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
        }

        .hero-list-item {
            position: relative;
            display: block;
            padding: 6px 10px;
            margin: 2px 0;
            background: #f9f9f9;
            color: #333;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            text-align: left;
            white-space: nowrap;
            border: 1px solid #e0e0e0;
        }

        .hero-list-item:hover {
            background: #1890ff;
            color: white;
        }

        /* 空槽位提示样式 */
        .slot-empty {
            color: #999;
            font-size: 12px;
            margin-top: 5px;
            line-height: 1.4;
        }

        .slot-content {
            padding-top: 18px;
        }

        .slot-name-red {
            font-weight: 600;
            font-size: 20px;
            color: red;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 6px;
        }
        .slot-name-blue {
            font-weight: 600;
            font-size: 20px;
            color: blue;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 6px;
        }

        .slot-title {
            font-size: 9px;
            color: #666;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* 提示和日志 */
        .team-full-alert {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #ff4d4f;
            color: white;
            padding: 10px 16px;
            border-radius: 6px;
            font-size: 14px;
            z-index: 1000;
            display: none;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateX(-50%) translateY(-20px);
            }

            to {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }
        }

        /* 战斗日志样式 */
        .battle-log-ai {
            color: #1890ff;
            font-weight: 600;
        }

        .battle-log-red {
            color: #ff4d4f;
            font-weight: 500;
        }

        .battle-log-blue {
            color: #1890ff;
            font-weight: 500;
        }

        .battle-log-highlight {
            background-color: #fffbe6;
            border-left: 3px solid #faad14;
            animation: pulse 1s ease;
        }

        @keyframes pulse {
            0% {
                background-color: #fffbe6;
            }

            50% {
                background-color: #fff7e6;
            }

            100% {
                background-color: #fffbe6;
            }
        }

        /* 通知提示样式 */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .notification.show {
            transform: translateX(0);
            opacity: 1;
        }

        .notification.success {
            background-color: #52c41a;
            border-left: 3px solid #389e0d;
        }

        .notification.error {
            background-color: #ff4d4f;
            border-left: 3px solid #cf1322;
        }

        .notification.warning {
            background-color: #faad14;
            border-left: 3px solid #d48806;
        }

        .notification.info {
            background-color: #1890ff;
            border-left: 3px solid #096dd9;
        }

        .battle-log-random {
            color: #722ed1;
            font-weight: 600;
        }

        /* 按钮样式增强 */
        .btn-primary,
        .btn-secondary,
        .btn-neutral {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .btn-primary:hover,
        .btn-secondary:hover,
        .btn-neutral:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .btn-primary:active,
        .btn-secondary:active,
        .btn-neutral:active {
            transform: translateY(0);
        }

        /* 响应式优化 */
        @media (max-width: 768px) {
            .hero-grid {
                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
                gap: 10px;
            }

            .hero-card {
                height: 160px;
                padding: 8px;
            }

            .hero-avatar {
                width: 50px;
                height: 50px;
            }

            .formation-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .container {
                padding-left: 10px;
                padding-right: 10px;
            }
        }

        /* 加载动画 */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #1890ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* 英雄详情动画 */
        #hero-detail {
            transition: all 0.3s ease;
        }

        /* 滚动条样式优化 */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>

<body class="bg-gray-100 p-4">
    <!-- 队伍满员提示 -->
    <div class="team-full-alert" id="team-alert">该队伍已填满！</div>

    <div class="container mx-auto max-w-7xl">
        <!-- 标题区域 -->
        <header class="text-center mb-6">
            <h1 class="text-3xl font-bold text-red-800">古代历史英雄战争AI分析</h1>
            <p class="text-gray-600 mt-2">点击阵容位置 → 选择英雄 → 组建10人队伍 → 开始AI分析战斗 | 支持随机分配阵营</p>
        </header>

        <!-- 主内容区域 -->
        <div class="flex flex-col lg:flex-row gap-6 justify-center">
            <!-- VS阵容配置 -->
            <div class="w-full lg:w-2/3 flex flex-col lg:flex-row gap-6">
                <!-- 红方阵容 -->
                <div class="w-full lg:w-1/2 bg-white rounded-xl p-5 shadow-md">
                    <h2 class="text-2xl font-bold text-red-600 mb-4 text-center">红方阵容</h2>
                    <div id="red-formation" class="formation-grid">
                        <!-- 10个阵容槽位 -->
                        <div class="formation-slot bg-red-50" data-team="red" data-index="0">
                            <div class="slot-content">
                                <div class="slot-category">君主</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="1">
                            <div class="slot-content">
                                <div class="slot-category">统帅</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="2">
                            <div class="slot-content">
                                <div class="slot-category">冲锋</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="3">
                            <div class="slot-content">
                                <div class="slot-category">守城</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="4">
                            <div class="slot-content">
                                <div class="slot-category">谋士</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="5">
                            <div class="slot-content">
                                <div class="slot-category">后勤</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="6">
                            <div class="slot-content">
                                <div class="slot-category">军医</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="7">
                            <div class="slot-content">
                                <div class="slot-category">斥候</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="8">
                            <div class="slot-content">
                                <div class="slot-category">政务</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-red-50" data-team="red" data-index="9">
                            <div class="slot-content">
                                <div class="slot-category">外交</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                    </div>
                    <div class="text-center mt-3">
                        <span class="font-bold">已选: </span>
                        <span id="red-count">0</span>/10
                    </div>
                </div>

                <!-- VS标志 -->
                <div class="hidden lg:flex items-center justify-center">
                    <div class="text-4xl font-bold text-gray-600 px-4 py-8 rounded-lg bg-gray-100">VS</div>
                </div>

                <!-- 蓝方阵容 -->
                <div class="w-full lg:w-1/2 bg-white rounded-xl p-5 shadow-md">
                    <h2 class="text-2xl font-bold text-blue-600 mb-4 text-center">蓝方阵容</h2>
                    <div id="blue-formation" class="formation-grid">
                        <!-- 10个阵容槽位 -->
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="0">
                            <div class="slot-content">
                                <div class="slot-category">君主</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="1">
                            <div class="slot-content">
                                <div class="slot-category">统帅</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="2">
                            <div class="slot-content">
                                <div class="slot-category">冲锋</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="3">
                            <div class="slot-content">
                                <div class="slot-category">守城</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="4">
                            <div class="slot-content">
                                <div class="slot-category">谋士</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="5">
                            <div class="slot-content">
                                <div class="slot-category">后勤</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="6">
                            <div class="slot-content">
                                <div class="slot-category">军医</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="7">
                            <div class="slot-content">
                                <div class="slot-category">斥候</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="8">
                            <div class="slot-content">
                                <div class="slot-category">政务</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                        <div class="formation-slot bg-blue-50" data-team="blue" data-index="9">
                            <div class="slot-content">
                                <div class="slot-category">外交</div>
                                <div class="slot-empty"></div>
                            </div>
                        </div>
                    </div>
                    <div class="text-center mt-3">
                        <span class="font-bold">已选: </span>
                        <span id="blue-count">0</span>/10
                    </div>
                </div>
            </div>
        </div>

        <!-- 战斗控制和日志 -->
        <div class="mt-6">
            <!-- 战斗控制 -->
            <div class="text-center flex flex-wrap gap-3 justify-center mb-6">
                <button id="random-teams"
                    class="px-6 py-3 text-white rounded-lg font-bold hover:bg-purple-700 active:bg-purple-800 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                    style="background-color: #722ed1;">
                    <i class="fa fa-random mr-2"></i>随机分配阵营
                </button>
                <button id="start-battle"
                    class="px-6 py-3 bg-red-700 text-white rounded-lg font-bold hover:bg-red-800 disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled>
                    <i class="fa fa-play mr-2"></i>开始AI战斗分析
                </button>
                <button id="reset-game" class="px-6 py-3 bg-gray-600 text-white rounded-lg font-bold hover:bg-gray-700">
                    <i class="fa fa-refresh mr-2"></i>重置游戏
                </button>
            </div>

            <!-- 战斗日志 -->
            <div class="bg-white rounded-xl p-5 shadow-md">
                <h2 class="text-2xl font-bold text-red-700 mb-4">AI战斗分析日志</h2>
                <div id="battle-log" class="h-[400px] overflow-y-auto bg-gray-50 p-3 rounded-lg text-sm">
                    <div class="text-center text-gray-500">战斗尚未开始</div>
                    <div class="mt-4 text-left text-xs text-gray-500">
                        <p>• 组建10人红方和10人蓝方阵容后可开始战斗</p>
                        <p>• 点击"随机分配阵营"可自动分配20位英雄到双方阵营</p>
                        <p>• AI将分析双方英雄属性、战术匹配度</p>
                        <p>• 战斗采用回合制，每回合输出关键战况</p>
                        <p>• 最终根据综合战力和战术配合判定胜负</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>

    <script>
        // 古代英雄战争模拟 - 优化版

        // 模块化设计 - 使用命名空间组织代码
        let heroTooltip = null;

        const WarSimulation = {
            // 完整的20位历史英雄数据
            heroes: [],
            // 游戏状态数据
            state: {
                redTeam: Array(10).fill(null),    // 红方阵容（10个槽位）
                blueTeam: Array(10).fill(null),   // 蓝方阵容（10个槽位）
                battleInProgress: false,          // 战斗是否进行中
                randomizingInProgress: false,     // 随机分配是否进行中
                currentStepIndex: 0               // 当前战斗步骤索引
            },

            // 常量配置
            config: {
                MAX_TEAM_SIZE: 10,
                BATTLE_ROUNDS: 5,
                ANIMATION_DURATION: 300,
                LOG_HIGHLIGHT_CLASS: 'battle-log-highlight',
                TEAM_COLORS: {
                    red: '#ff4d4f',
                    blue: '#1890ff'
                }
            },

            // 初始化游戏
            init() {
                // 页面加载完成后初始化
                const self = this; // 保存当前this引用
                document.addEventListener('DOMContentLoaded', () => {
                    // 加载英雄数据
                    WarSimulation.heroes = GLOBAL_HEROES;
                    
                    // 直接使用随机分配功能，不渲染英雄池
                    initEventListeners(); // 初始化事件监听（直接调用全局函数）
                    updateTeamCounts(); // 初始化队伍计数（直接调用全局函数）

                    // 创建英雄详情提示框
                    if (!heroTooltip) {
                        heroTooltip = document.createElement('div');
                        heroTooltip.id = 'hero-tooltip';
                        heroTooltip.className = 'hero-tooltip';
                        document.body.appendChild(heroTooltip);
                    }

                    // 显示页面加载完成动画
                    showNotification('欢迎来到古代英雄战争模拟！鼠标悬停类别可查看可选英雄', 'success');
                });
            }
        }
        // 将英雄添加到指定队伍
        // 英雄池功能已移除，现在仅通过随机分配按钮组建队伍

        // 获取指定类别的所有英雄
        function getHeroesByCategory(category) {
            return GLOBAL_HEROES.filter(hero => hero.category === category);
        }

        // 创建英雄列表弹出框 - 圆形分布
        function createHeroListPopup(category, team, index) {
            const heroes = getHeroesByCategory(category);
            if (heroes.length === 0) return '';

            // 创建所有英雄按钮，普通列表展示
            const heroItems = heroes.map((hero, idx) => 
                `<div class="hero-list-item" data-hero-id="${hero.id}" data-index="${idx}">${hero.name}</div>`
            ).join('');

            return `<div class="hero-list-popup" data-category="${category}" data-hero-count="${heroes.length}">${heroItems}</div>`;
        }

        // 隐藏所有弹出框
        function hideAllPopups() {
            document.querySelectorAll('.hero-list-popup.show').forEach(popup => {
                popup.classList.remove('show');
            });
            if (heroTooltip) {
                heroTooltip.classList.remove('show');
            }
        }

        // 设置弹出框位置（在类别名称按钮旁边）
        function positionHeroButtonsInCircle(popup, slot) {
            if (!popup) return;
            
            // 获取类别名称的位置
            const categoryLabel = slot.querySelector('.slot-category');
            if (!categoryLabel) return;
            
            const slotRect = slot.getBoundingClientRect();
            const categoryRect = categoryLabel.getBoundingClientRect();
            
            // 计算类别名称相对于槽位的位置
            const categoryRight = categoryRect.right - slotRect.left; // 类别名称右边缘
            const categoryTop = categoryRect.top - slotRect.top; // 类别名称顶部
            
            // 弹出框显示在类别名称右侧
            popup.style.left = `${categoryRight + 8}px`;
            popup.style.top = `${categoryTop - 6}px`;
            
            // 移除所有按钮的绝对定位样式，让它们正常排列
            const heroItems = popup.querySelectorAll('.hero-list-item');
            heroItems.forEach((item) => {
                item.style.position = 'relative';
                item.style.left = 'auto';
                item.style.top = 'auto';
                item.style.transform = 'none';
                item.style.animationDelay = '0s';
                if (!item.dataset.tooltipBound) {
                    item.addEventListener('mouseenter', handleHeroItemMouseEnter);
                    item.addEventListener('mouseleave', handleHeroItemMouseLeave);
                    item.dataset.tooltipBound = 'true';
                }
            });
        }

        function handleHeroItemMouseEnter(event) {
            if (!heroTooltip) return;
            const heroId = event.currentTarget.getAttribute('data-hero-id');
            const hero = GLOBAL_HEROES.find(h => h.id === heroId);
            if (!hero) return;

            //添加biography、avatar、era
            const biography = hero.biography ? hero.biography : '';
            const avatar = hero.avatar ? hero.avatar : '';
            const era = hero.era ? hero.era : '';

            const stats = hero.stats ? `武:${hero.stats.force} 智:${hero.stats.intellect} 统:${hero.stats.command} 政:${hero.stats.politics}` : '';
            const title = hero.title ? hero.title : '';
            const specialty = hero.specialty ? hero.specialty : '';

            heroTooltip.innerHTML = `
                <div class="hero-tooltip-name">${hero.name}${era ? ' · ' + era : ''}${title ? ' · ' + title : ''}</div>
                ${stats ? `<div class="hero-tooltip-stats">${stats}</div>` : ''}
                ${specialty ? `<div class="hero-tooltip-specialty">${specialty}</div>` : ''}
                ${biography ? `<div class="hero-tooltip-biography">${biography}</div>` : ''}
                ${avatar ? `<div class="hero-tooltip-avatar"><img src="${avatar}" alt="${hero.name}" /></div>` : ''}
            `;

            const rect = event.currentTarget.getBoundingClientRect();
            const tooltipX = rect.right + 12 + window.scrollX;
            const tooltipY = rect.top + window.scrollY;

            heroTooltip.style.left = `${tooltipX}px`;
            heroTooltip.style.top = `${tooltipY}px`;
            heroTooltip.classList.add('show');
        }

        function handleHeroItemMouseLeave() {
            if (!heroTooltip) return;
            heroTooltip.classList.remove('show');
        }

        // 更新阵容槽位显示
        function updateSlotDisplay(team, index, hero = null) {
            const slot = document.querySelector(`.formation-slot[data-team="${team}"][data-index="${index}"]`);

            // 根据索引获取对应的分类名称
            const categories = ['君主', '统帅', '冲锋', '守城', '谋士', '后勤', '军医', '斥候', '政务', '外交'];
            const categoryName = categories[index];

            if (!hero) {
                // 清空槽位
                slot.classList.remove('slot-occupied');
                const heroListPopup = createHeroListPopup(categoryName, team, index);
                slot.innerHTML = `
                    <div class="slot-content">
                        <div class="slot-category">${categoryName}</div>
                        <div class="slot-empty"></div>
                        ${heroListPopup}
                    </div>
                `;
                
                // 绑定英雄列表点击事件
                bindHeroListEvents(slot, team, index, categoryName);
                return;
            }

            // 显示英雄信息
            slot.classList.add('slot-occupied');
            const heroListPopup = createHeroListPopup(categoryName, team, index);
            slot.innerHTML = `
                <div class="slot-content">
                    <div class="slot-category">${categoryName}</div>
                    <div class="slot-name-${team=='red' ? 'red' : 'blue'}">${hero.name}</div>
                    <div class="slot-title">${hero.title}</div>
                    ${heroListPopup}
                </div>
            `;
            
            // 绑定英雄列表点击事件
            bindHeroListEvents(slot, team, index, categoryName);
        }

        // 绑定英雄列表事件
        function bindHeroListEvents(slot, team, index, categoryName) {
            // 移除旧的事件监听器（如果存在）
            if (slot._unifiedClickHandler) {
                slot.removeEventListener('click', slot._unifiedClickHandler);
            }
            if (slot._documentClickHandler) {
                document.removeEventListener('click', slot._documentClickHandler);
            }
            
            // 统一的点击事件处理器
            slot._unifiedClickHandler = function(e) {
                const categoryLabel = slot.querySelector('.slot-category');
                const popup = slot.querySelector('.hero-list-popup');
                const heroItem = e.target.closest('.hero-list-item');
                
                // 如果点击的是英雄按钮
                if (heroItem) {
                    e.stopPropagation();
                    const heroId = heroItem.getAttribute('data-hero-id');
                    const hero = GLOBAL_HEROES.find(h => h.id === heroId);
                    if (hero) {
                        // 隐藏弹出框
                        if (popup) {
                            popup.classList.remove('show');
                        }
                        if (heroTooltip) {
                            heroTooltip.classList.remove('show');
                        }
                        
                        // 将英雄添加到对应位置
                        const slotTeam = slot.getAttribute('data-team');
                        const slotIndex = parseInt(slot.getAttribute('data-index'));
                        const categories = ['君主', '统帅', '冲锋', '守城', '谋士', '后勤', '军医', '斥候', '政务', '外交'];
                        const slotCategory = categories[slotIndex];
                        
                        if (slotTeam === 'red') {
                            WarSimulation.state.redTeam[slotIndex] = hero;
                        } else {
                            WarSimulation.state.blueTeam[slotIndex] = hero;
                        }
                        updateSlotDisplay(slotTeam, slotIndex, hero);
                        updateTeamCounts();
                        checkBattleReady();
                        showNotification(`${hero.name}已加入${slotTeam === 'red' ? '红方' : '蓝方'}${slotCategory}位置`, 'success');
                    }
                    return;
                }
                
                // 如果点击的是类别标签
                if (categoryLabel && categoryLabel.contains(e.target)) {
                    e.stopPropagation();
                    // 先隐藏所有其他弹出框
                    hideAllPopups();
                    
                    if (popup) {
                        if (popup.classList.contains('show')) {
                            // 如果已显示，则隐藏
                            popup.classList.remove('show');
                        } else {
                            // 如果未显示，则显示并计算位置
                            positionHeroButtonsInCircle(popup, slot);
                            popup.classList.add('show');
                        }
                    }
                    return;
                }
                
                // 如果点击的是槽位其他区域（不是类别标签和按钮）
                if (!categoryLabel.contains(e.target) && !heroItem && popup) {
                    // 先隐藏所有其他弹出框
                    hideAllPopups();
                    
                    if (popup.classList.contains('show')) {
                        popup.classList.remove('show');
                        if (heroTooltip) {
                            heroTooltip.classList.remove('show');
                        }
                    } else {
                        positionHeroButtonsInCircle(popup, slot);
                        popup.classList.add('show');
                    }
                }
            };
            slot.addEventListener('click', slot._unifiedClickHandler);

            // 点击页面其他地方时隐藏所有弹出框
            slot._documentClickHandler = function(e) {
                const popup = slot.querySelector('.hero-list-popup');
                if (popup && popup.classList.contains('show')) {
                    // 如果点击的不是槽位、弹出框或按钮，则隐藏
                    if (!slot.contains(e.target) && !popup.contains(e.target)) {
                        hideAllPopups();
                    }
                }
            };
            document.addEventListener('click', slot._documentClickHandler);
        }

        // 从队伍中移除英雄
        // 英雄池功能已移除，现在仅通过随机分配按钮组建队伍，通过重置按钮清空队伍

        // 更新队伍计数
        function updateTeamCounts() {
            const redCount = WarSimulation.state.redTeam.filter(hero => hero !== null).length;
            const blueCount = WarSimulation.state.blueTeam.filter(hero => hero !== null).length;

            document.getElementById('red-count').textContent = redCount;
            document.getElementById('blue-count').textContent = blueCount;
        }

        // 显示队伍满员提示
        function showTeamFullAlert(message) {
            const alert = document.getElementById('team-alert');
            alert.textContent = message;
            alert.style.display = 'block';

            setTimeout(() => {
                alert.style.display = 'none';
            }, 2000);
        }

        // 检查战斗是否准备就绪
        function checkBattleReady() {
            const redCount = WarSimulation.state.redTeam.filter(hero => hero !== null).length;
            const blueCount = WarSimulation.state.blueTeam.filter(hero => hero !== null).length;
            const startButton = document.getElementById('start-battle');
            const randomButton = document.getElementById('random-teams');

            startButton.disabled = !(redCount === 10 && blueCount === 10 && !WarSimulation.state.battleInProgress && !WarSimulation.state.randomizingInProgress);
            randomButton.disabled = WarSimulation.state.battleInProgress || WarSimulation.state.randomizingInProgress;
        }

        // 添加战斗日志 - 增强版，支持脉冲高亮动画
        function addBattleLog(message, isHighlight = false) {
            const logContainer = document.getElementById('battle-log');
            const now = new Date();
            const timeStr = now.toLocaleTimeString('zh-CN');

            // 如果是初始状态，先清空
            if (logContainer.querySelector('.text-gray-500') && !WarSimulation.state.battleInProgress && !WarSimulation.state.randomizingInProgress && !logContainer.querySelector('.battle-log-ai')) {
                logContainer.innerHTML = '';
            }

            const logItem = document.createElement('div');
            logItem.className = `mb-2 p-2 bg-white rounded border border-gray-200 transition-all duration-300 ${isHighlight ? 'battle-log-highlight' : ''}`;

            // 添加脉冲动画效果
            if (isHighlight) {
                setTimeout(() => {
                    logItem.classList.remove('battle-log-highlight');
                    logItem.classList.add('battle-log-normal');
                }, 1500);
            }
            logItem.innerHTML = `<span class="text-gray-500 text-xs">[${timeStr}]</span> ${message}`;

            logContainer.appendChild(logItem);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        // 随机分配阵营 - 增强版，添加用户通知
        function randomizeTeams() {
            console.log('随机分配按钮被点击，开始执行随机分配功能');

            if (WarSimulation.state.randomizingInProgress || WarSimulation.state.battleInProgress) {
                console.log('随机分配被跳过，当前状态：randomizingInProgress=' + WarSimulation.state.randomizingInProgress + ', battleInProgress=' + WarSimulation.state.battleInProgress);
                return;
            }

            // 标记为正在随机分配
            WarSimulation.state.randomizingInProgress = true;

            // 显示开始随机分配的通知
            showNotification('开始随机分配阵营...', 'info');
            checkBattleReady();

            // 清空现有阵容
            addBattleLog('<span class="battle-log-random">[随机分配开始]</span> 正在清空现有阵容...', true);

            setTimeout(() => {
                // 重置阵容数据
                WarSimulation.state.redTeam = Array(10).fill(null);
                WarSimulation.state.blueTeam = Array(10).fill(null);

                console.log('阵容数据已重置，英雄数量：' + WarSimulation.heroes.length);

                // 清空UI显示
                document.querySelectorAll('.formation-slot').forEach((slot, idx) => {
                    slot.classList.remove('slot-occupied');
                    const team = slot.getAttribute('data-team');
                    const index = parseInt(slot.getAttribute('data-index'));
                    updateSlotDisplay(team, index, null);
                });

                updateTeamCounts();

                // 定义阵容面板的10个类别顺序
                const formationCategories = ['君主', '统帅', '冲锋', '守城', '谋士', '后勤', '军医', '斥候', '政务', '外交'];
                
                addBattleLog('<span class="battle-log-random">[随机分配]</span> 现有阵容已清空，开始按阵容面板类别顺序随机分配英雄...', true);

                // 用于存储已选英雄，避免重复选择
                const selectedHeroIds = new Set();
                
                // 按阵容面板类别顺序，为每个位置随机选择一个对应类别的英雄
                const redHeroes = [];
                const blueHeroes = [];
                
                formationCategories.forEach((category, categoryIndex) => {
                    // 获取该类别的所有英雄
                    const categoryHeroes = WarSimulation.heroes.filter(hero => hero.category === category);
                    
                    if (categoryHeroes.length > 0) {
                        // 过滤出未被选中的英雄
                        const availableHeroes = categoryHeroes.filter(hero => !selectedHeroIds.has(hero.id));
                        
                        if (availableHeroes.length > 0) {
                            // 为红队随机选择一个该类别的英雄
                            const redShuffled = [...availableHeroes].sort(() => Math.random() - 0.5);
                            const redSelectedHero = redShuffled[0];
                            redHeroes.push(redSelectedHero);
                            selectedHeroIds.add(redSelectedHero.id);
                            
                            // 为蓝队随机选择一个该类别的英雄
                            const blueAvailableHeroes = availableHeroes.filter(hero => hero.id !== redSelectedHero.id);
                            if (blueAvailableHeroes.length > 0) {
                                const blueShuffled = [...blueAvailableHeroes].sort(() => Math.random() - 0.5);
                                const blueSelectedHero = blueShuffled[0];
                                blueHeroes.push(blueSelectedHero);
                                selectedHeroIds.add(blueSelectedHero.id);
                            } else {
                                // 如果没有足够的英雄，记录警告
                                console.warn(`类别${category}英雄数量不足，无法为蓝队分配不同的英雄`);
                                blueHeroes.push(null);
                            }
                        } else {
                            console.warn(`类别${category}没有可用的英雄`);
                            redHeroes.push(null);
                            blueHeroes.push(null);
                        }
                    } else {
                        console.warn(`未找到类别${category}的英雄`);
                        redHeroes.push(null);
                        blueHeroes.push(null);
                    }
                });

                console.log('按阵容面板类别分配完成，红方：' + redHeroes.filter(h => h !== null).length + '人，蓝方：' + blueHeroes.filter(h => h !== null).length + '人');

                // 批量添加红方英雄（带延迟，让日志逐条显示）
                addBattleLog('<span class="battle-log-random">[随机分配]</span> 开始分配<span class="text-red-600">红方</span>英雄：', true);

                setTimeout(() => {
                    redHeroes.forEach((hero, index) => {
                        setTimeout(() => {
                            WarSimulation.state.redTeam[index] = hero;
                            updateSlotDisplay('red', index, hero);
                            addBattleLog(`<span class="battle-log-random">[随机分配]</span> <span class="text-red-600">红方</span>${index + 1}号位：${hero.name}（${hero.title}，${hero.category}）`);

                            // 最后一个英雄添加完成后
                            if (index === redHeroes.length - 1) {
                                setTimeout(() => {
                                    addBattleLog('<span class="battle-log-random">[随机分配]</span> 开始分配<span class="text-blue-600">蓝方</span>英雄：', true);

                                    // 批量添加蓝方英雄（带延迟）
                                    blueHeroes.forEach((blueHero, blueIndex) => {
                                        setTimeout(() => {
                                            WarSimulation.state.blueTeam[blueIndex] = blueHero;
                                            updateSlotDisplay('blue', blueIndex, blueHero);
                                            addBattleLog(`<span class="battle-log-random">[随机分配]</span> <span class="text-blue-600">蓝方</span>${blueIndex + 1}号位：${blueHero.name}（${blueHero.title}，${blueHero.category}）`);

                                            // 最后一个英雄添加完成后
                                            if (blueIndex === blueHeroes.length - 1) {
                                                setTimeout(() => {
                                                    updateTeamCounts();
                                                    checkBattleReady();

                                                    // 统计双方阵容信息（按type统计）
                                                    const redGenerals = WarSimulation.state.redTeam.filter(h => h.type === 'general').length;
                                                    const redMinisters = WarSimulation.state.redTeam.filter(h => h.type === 'minister').length;
                                                    const redEmperors = WarSimulation.state.redTeam.filter(h => h.type === 'emperor').length;
                                                    const blueGenerals = WarSimulation.state.blueTeam.filter(h => h.type === 'general').length;
                                                    const blueMinisters = WarSimulation.state.blueTeam.filter(h => h.type === 'minister').length;
                                                    const blueEmperors = WarSimulation.state.blueTeam.filter(h => h.type === 'emperor').length;
                                                     
                                                    // 按category统计双方阵容
                                                    const redCategories = {};
                                                    const blueCategories = {};
                                                    
                                                    WarSimulation.state.redTeam.forEach(hero => {
                                                        redCategories[hero.category] = (redCategories[hero.category] || 0) + 1;
                                                    });
                                                    
                                                    WarSimulation.state.blueTeam.forEach(hero => {
                                                        blueCategories[hero.category] = (blueCategories[hero.category] || 0) + 1;
                                                    });

                                                    addBattleLog('<span class="battle-log-random">[随机分配完成]</span> 双方阵容分配完毕！', true);
                                                    addBattleLog(`<span class="battle-log-random">[阵容统计]</span> <span class="text-red-600">红方</span>：武将${redGenerals}人，文臣${redMinisters}人，帝王${redEmperors}人`);
                                                    addBattleLog(`<span class="battle-log-random">[阵容统计]</span> <span class="text-blue-600">蓝方</span>：武将${blueGenerals}人，文臣${blueMinisters}人，帝王${blueEmperors}人`);
                                                     
                                                    // 显示类别分布统计
                                                    const redCategoryStats = Object.entries(redCategories)
                                                        .map(([category, count]) => `${category}${count}人`)
                                                        .join('，');
                                                    const blueCategoryStats = Object.entries(blueCategories)
                                                        .map(([category, count]) => `${category}${count}人`)
                                                        .join('，');
                                                    
                                                    addBattleLog(`<span class="battle-log-random">[类别分布]</span> <span class="text-red-600">红方</span>：${redCategoryStats}`);
                                                    addBattleLog(`<span class="battle-log-random">[类别分布]</span> <span class="text-blue-600">蓝方</span>：${blueCategoryStats}`);
                                                    
                                                    addBattleLog('<span class="battle-log-random">[提示]</span> 可点击"开始AI战斗分析"进行对战模拟！', true);

                                                    WarSimulation.state.randomizingInProgress = false;
                                                    checkBattleReady();
                                                }, 5);
                                            }
                                        }, 5);
                                    });
                                }, 8);
                            }
                        }, index * 4); // 每个英雄间隔400ms
                    });
                }, 5);
            }, 8);
        }

        // 新增：逐字流式输出到日志面板
        function streamBattleLog(text, cssClass = '') {

            const logPanel = document.getElementById('battle-log');
            // 若当前无临时行，则新建
            if (!logPanel._streamLine) {
                logPanel._streamLine = document.createElement('div');
                logPanel._streamLine.className = cssClass;
                logPanel.appendChild(logPanel._streamLine);
            }
            logPanel._streamLine.innerHTML += text;
            logPanel.scrollTop = logPanel.scrollHeight;
        }

        // 新增：结束当前流式行
        function endStreamLine() {
            const logPanel = document.getElementById('battle-log');
            if (logPanel._streamLine) {
                logPanel._streamLine = null;
            }
        }
        // 调用AI接口进行战斗分析
        async function callAIBattleAnalysis(redTeam, blueTeam) {
            try {
                // 显示AI分析开始
                addBattleLog('<span class="battle-log-ai">[AI战斗分析开始]</span> 正在初始化分析...', true);

                // 准备发送给AI的数据
                const redTeamInfo = redTeam.map(hero => `${hero.name}（位置：${hero.category}）`).join('\n');
                const blueTeamInfo = blueTeam.map(hero => `${hero.name}（位置：${hero.category}）`).join('\n');

                // 构建提示词
                const prompt = `红方阵容：\n${redTeamInfo}\n\n蓝方阵容：\n${blueTeamInfo}\n给出红蓝双方对比评分、关键因素、胜负结果、综合评分。`;
                console.log('提示词:', prompt);

                // 配置API密钥（默认使用空字符串，用户需要替换为有效值）
                const apiKey = 'sk-xxxxxx'; // 请替换为实际的API密钥


                addBattleLog('<span class="battle-log-ai">[AI分析中]</span> 正在发送请求到AI服务器...', true);
                var myHeaders = new Headers();
                myHeaders.append("Authorization", `Bearer ${apiKey}`);
                myHeaders.append("Content-Type", "application/json");

                var raw = JSON.stringify({
                    "model": "qwen-plus",
                    "messages": [
                        {
                            "role": "system",
                            "content": "你是一个历史军事分析专家，擅长模拟历史战争场景下的战斗过程。"
                        },
                        {
                            "role": "user",
                            "content": prompt
                        }
                    ],
                    "stream": true,
                    "stream_options": {
                        "include_usage": true
                    }
                });

                var requestOptions = {
                    method: 'POST',
                    headers: myHeaders,
                    body: raw,
                    redirect: 'follow'
                };

                // 改造 fetch 流式读取
                fetch("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", requestOptions)
                    .then(response => {
                        const reader = response.body.getReader();
                        const decoder = new TextDecoder('utf-8');
                        function read() {
                            reader.read().then(({ done, value }) => {
                                if (done) {
                                    endStreamLine();          // 流结束，换行
                                    return;
                                }
                                const chunk = decoder.decode(value, { stream: true });
                                // SSE 格式解析：data: {...}
                                const lines = chunk.split('\n');
                                lines.forEach(line => {
                                    if (line.startsWith('data:')) {
                                        try {
                                            const jsonStr = line.slice(5).trim();
                                            if (jsonStr === '[DONE]'){
                                                WarSimulation.state.battleInProgress = false;
                                                checkBattleReady(); // 重新启用开始按钮
                                                addBattleLog('<span class="battle-log-ai">[AI战斗分析结束]</span> 可点击"重置游戏"开始新的战斗！', true);

                                                // 战斗结束后显示通知
                                                setTimeout(() => {
                                                    showNotification('战斗分析完成！点击"重置游戏"开始新的战斗', 'info');
                                                }, 2000);
                                                return;
                                            }
                                            const data = JSON.parse(jsonStr);
                                            const delta = data.choices[0].delta.content;
                                            if (delta) {
                                                // 对返回结果中的 \n\n---\n\n 进行格式化显示
                                                const formattedDelta = delta
                                                    .replace(/\n\n---\n\n/g, '<hr class="my-4 border-gray-300">')
                                                    .replace(/\n\n/g, '<br/>')
                                                    .replace(/\n/g, '<br/>');
                                                streamBattleLog(formattedDelta, 'battle-log-ai');
                                            }
                                        } catch (e) {
                                            // 忽略非 JSON 行
                                        }
                                    }
                                });
                                read(); // 继续读取下一块
                            });
                        }
                        read();
                    })
                    .catch(error => {
                        endStreamLine();
                        console.log('error', error);
                        addBattleLog(`<span class="battle-log-ai">[错误]</span> AI API调用失败，将使用本地分析: ${error.message}`, true);
                    });
            } catch (error) {
                console.error('AI API调用失败:', error);
                addBattleLog(`<span class="battle-log-ai">[错误]</span> AI API调用失败，将使用本地分析: ${error.message}`, true);

            }
        }

        // 生成模拟的AI分析结果（当OpenAI API不可用时）
        function generateMockAnalysisResult(redTeam, blueTeam) {
            // 计算基本战力
            const redPower = calculateTeamPower(redTeam);
            const bluePower = calculateTeamPower(blueTeam);

            // 分析阵容特点
            const redGenerals = redTeam.filter(h => h.type === 'general').length;
            const blueGenerals = blueTeam.filter(h => h.type === 'general').length;
            const redMinisters = redTeam.filter(h => h.type === 'minister').length;
            const blueMinisters = blueTeam.filter(h => h.type === 'minister').length;
            const redHasEmperor = redTeam.some(h => h.type === 'emperor');
            const blueHasEmperor = blueTeam.some(h => h.type === 'emperor');

            // 生成战术分析笔记
            const specialNotes = [];
            if (redHasEmperor || blueHasEmperor) {
                specialNotes.push(redHasEmperor && blueHasEmperor ? "双方均有帝王，领导力将是关键因素" :
                    redHasEmperor ? "红方有帝王坐镇，士气和指挥体系更占优势" :
                        "蓝方有帝王坐镇，士气和指挥体系更占优势");
            }
            if (redMinisters > blueMinisters * 2) {
                specialNotes.push("红方谋士数量占优，可能在战术层面有更多变化");
            } else if (blueMinisters > redMinisters * 2) {
                specialNotes.push("蓝方谋士数量占优，可能在战术层面有更多变化");
            }
            if (redGenerals > blueGenerals * 2) {
                specialNotes.push("红方武将众多，在正面交锋中可能占据优势");
            } else if (blueGenerals > redGenerals * 2) {
                specialNotes.push("蓝方武将众多，在正面交锋中可能占据优势");
            }

            // 确定模拟的战斗结果
            let winner = 'tie';
            let winningMargin = 0;
            let battleRounds = [];

            // 基于战力差异确定胜者
            if (Math.abs(redPower - bluePower) > 30) {
                winner = redPower > bluePower ? 'red' : 'blue';
                winningMargin = Math.abs(redPower - bluePower);
            }

            // 战斗详情模板
            const battleDetails = {
                red: [
                    "英勇冲锋，势不可挡！",
                    "巧妙运用战术，打乱敌军阵脚！",
                    "士气高涨，一鼓作气击败对手！"
                ],
                blue: [
                    "战术精湛，以智取胜！",
                    "防守稳固，反击犀利！",
                    "团队配合默契，形成压倒性优势！"
                ],
                tie: [
                    "双方你来我往，互有攻守！",
                    "势均力敌，难分高下！",
                    "各有胜负，战斗进入僵持阶段！"
                ]
            };

            // 模拟5回合战斗
            for (let round = 1; round <= 5; round++) {
                // 随机选择参战英雄
                const redFighter = redTeam[Math.floor(Math.random() * redTeam.length)];
                const blueFighter = blueTeam[Math.floor(Math.random() * blueTeam.length)];

                // 计算战力，加入随机波动
                const redRoundPower = calculateHeroPower(redFighter) * (0.9 + Math.random() * 0.2);
                const blueRoundPower = calculateHeroPower(blueFighter) * (0.9 + Math.random() * 0.2);

                // 确定回合胜者
                let roundWinner = 'tie';
                if (redRoundPower > blueRoundPower * 1.1) roundWinner = 'red';
                else if (blueRoundPower > redRoundPower * 1.1) roundWinner = 'blue';

                // 随机选择战斗详情
                const detailIndex = Math.floor(Math.random() * battleDetails[roundWinner].length);

                battleRounds.push({
                    round: round,
                    redFighter: redFighter.name,
                    blueFighter: blueFighter.name,
                    redPower: Math.round(redRoundPower),
                    bluePower: Math.round(blueRoundPower),
                    winner: roundWinner,
                    details: battleDetails[roundWinner][detailIndex]
                });
            }

            // 生成胜利关键因素
            const criticalFactors = [];
            if (winner === 'red') {
                criticalFactors.push("红方综合战力更强");
                if (redHasEmperor) criticalFactors.push("帝王坐镇提升了军队凝聚力");
                if (redMinisters > blueMinisters) criticalFactors.push("谋士数量占优，战术运用更加灵活");
                if (redGenerals > blueGenerals) criticalFactors.push("武将众多，正面交锋占据优势");
            } else if (winner === 'blue') {
                criticalFactors.push("蓝方综合战力更强");
                if (blueHasEmperor) criticalFactors.push("帝王坐镇提升了军队凝聚力");
                if (blueMinisters > redMinisters) criticalFactors.push("谋士数量占优，战术运用更加灵活");
                if (blueGenerals > redGenerals) criticalFactors.push("武将众多，正面交锋占据优势");
            } else {
                criticalFactors.push("双方实力相当，各有优势");
                criticalFactors.push("战斗过程中战术运用都很出色");
            }

            return {
                status: 'success',
                analysis: {
                    lineupAnalysis: {
                        redTeam: {
                            totalPower: redPower,
                            generals: redGenerals,
                            ministers: redMinisters,
                            hasEmperor: redHasEmperor
                        },
                        blueTeam: {
                            totalPower: bluePower,
                            generals: blueGenerals,
                            ministers: blueMinisters,
                            hasEmperor: blueHasEmperor
                        }
                    },
                    tacticalAnalysis: {
                        powerDifference: redPower - bluePower,
                        powerEvaluation: Math.abs(redPower - bluePower) < 50 ? '势均力敌' : (redPower > bluePower ? '红方优势' : '蓝方优势'),
                        specialNotes: specialNotes
                    },
                    battleSimulation: battleRounds,
                    finalResult: {
                        winner: winner,
                        winningMargin: winningMargin,
                        criticalFactors: criticalFactors
                    }
                }
            };
        }

        // 当AI接口调用失败时的本地分析备选方案
        function generateLocalAnalysisResult(redTeam, blueTeam) {
            // 直接返回增强的模拟分析结果，确保返回格式一致且数据完整
            const mockResult = generateMockAnalysisResult(redTeam, blueTeam);
            return {
                status: 'fallback',
                analysis: mockResult.analysis
            };
        }

        // 开始AI战斗分析 - 使用AI接口版本
        async function startBattle() {
            if (WarSimulation.state.battleInProgress) return;

            // 显示战斗开始通知
            showNotification('战斗开始分析中...', 'info');

            WarSimulation.state.battleInProgress = true;
            checkBattleReady(); // 禁用开始按钮

            // 清空现有日志
            document.getElementById('battle-log').innerHTML = '';

            try {
                // 调用AI接口进行战斗分析
                callAIBattleAnalysis(WarSimulation.state.redTeam, WarSimulation.state.blueTeam);

            } catch (error) {
                console.error('战斗分析过程中出错:', error);
                addBattleLog(`<span class="battle-log-ai">[错误]</span> 战斗分析失败：${error.message}`, true);

                // 重置战斗状态
                WarSimulation.state.battleInProgress = false;
                checkBattleReady();
                showNotification('战斗分析失败，请重试', 'error');
            }
        }

        // 最终决战和结果判定
        function finalBattle() {
            addBattleLog('<span class="battle-log-ai">[最终决战]</span> 5回合激战结束，进入最终决战阶段！', true);

            const redFinalPower = calculateTeamPower(WarSimulation.state.redTeam) * (0.8 + Math.random() * 0.4); // 加入随机波动
            const blueFinalPower = calculateTeamPower(WarSimulation.state.blueTeam) * (0.8 + Math.random() * 0.4);

            addBattleLog(`<span class="battle-log-ai">[最终战力]</span> 红方：${Math.round(redFinalPower)} vs 蓝方：${Math.round(blueFinalPower)}`);
            addBattleLog('<span class="battle-log-ai">[AI最终分析]</span> 综合阵容、战术、实战表现进行最终判定...', true);

            setTimeout(() => {
                if (redFinalPower > blueFinalPower) {
                    addBattleLog(`<span class="battle-log-ai">[战斗结果]</span> 红方获胜！🎉`, true);
                    addBattleLog(`<span class="battle-log-red">红方凭借强大的综合战力和战术配合，最终击败蓝方！</span>`);
                    addBattleLog(`<span class="battle-log-ai">[AI总结]</span> 红方胜利关键因素：`);
                    addBattleLog(`- 总战力领先：${Math.round(redFinalPower - blueFinalPower)}点`);
                    addBattleLog(`- 武将配置合理，单挑能力突出`);
                    addBattleLog(`- 战术执行到位，团队配合默契`);
                    showNotification('红方获胜！🎉', 'success');
                } else if (blueFinalPower > redFinalPower) {
                    addBattleLog(`<span class="battle-log-ai">[战斗结果]</span> 蓝方获胜！🎉`, true);
                    addBattleLog(`<span class="battle-log-blue">蓝方凭借出色的智谋和战斗韧性，最终击败红方！</span>`);
                    addBattleLog(`<span class="battle-log-ai">[AI总结]</span> 蓝方胜利关键因素：`);
                    addBattleLog(`- 总战力领先：${Math.round(blueFinalPower - redFinalPower)}点`);
                    addBattleLog(`- 谋士智力超群，战术布局精妙`);
                    addBattleLog(`- 临场应变能力强，关键时刻发挥出色`);
                    showNotification('蓝方获胜！🎉', 'success');
                } else {
                    addBattleLog(`<span class="battle-log-ai">[战斗结果]</span> 双方战平！🤝`, true);
                    addBattleLog(`<span class="battle-log-ai">双方战力、战术、配合均势均力敌，最终握手言和！</span>`);
                    addBattleLog(`<span class="battle-log-ai">[AI总结]</span> 这是一场势均力敌的精彩对决，双方各有优劣，难分高下！`);
                    showNotification('双方战平！🤝', 'info');
                }

                WarSimulation.state.battleInProgress = false;
                checkBattleReady(); // 重新启用开始按钮
                addBattleLog('<span class="battle-log-ai">[AI战斗分析结束]</span> 可点击"重置游戏"开始新的战斗！', true);

                // 战斗结束后显示通知
                setTimeout(() => {
                    showNotification('战斗分析完成！点击"重置游戏"开始新的战斗', 'info');
                }, 2000);
            }, 2000);
        }

        // 计算单个英雄的战力
        function calculateHeroPower(hero) {
            return Math.round(
                hero.stats.force * 0.4 +    // 武力占比最高
                hero.stats.command * 0.3 +  // 统帅次之
                hero.stats.intellect * 0.2 + // 智力辅助
                hero.stats.politics * 0.1   // 政治影响最小
            );
        }

        // 计算队伍总战力
        function calculateTeamPower(team) {
            return team.reduce((total, hero) => {
                if (!hero) return total;
                return total + calculateHeroPower(hero);
            }, 0);
        }

        // 重置游戏 - 增强版，添加用户通知和确认流程优化
        function resetGame() {
            // 检查战斗状态并获取用户确认
            if (WarSimulation.state.battleInProgress && confirm('战斗正在进行中，确定要重置游戏吗？')) {
                WarSimulation.state.battleInProgress = false;
            } else if (WarSimulation.state.randomizingInProgress && confirm('随机分配正在进行中，确定要重置游戏吗？')) {
                WarSimulation.state.randomizingInProgress = false;
            } else if (!WarSimulation.state.battleInProgress && !WarSimulation.state.randomizingInProgress) {
                // 无需确认
            } else {
                return; // 用户取消重置
            }

            // 显示重置游戏通知
            showNotification('正在重置游戏...', 'info');

            // 1. 完全重置整个state对象，确保所有游戏状态都被清除
            WarSimulation.state = {
                redTeam: Array(10).fill(null),    // 红方阵容（10个槽位）
                blueTeam: Array(10).fill(null),   // 蓝方阵容（10个槽位）
                battleInProgress: false,          // 战斗是否进行中
                randomizingInProgress: false,     // 随机分配是否进行中
                currentStepIndex: 0               // 当前战斗步骤索引
            };

            // 2. 重置UI元素
            // 清空所有槽位
            document.querySelectorAll('.formation-slot').forEach((slot, idx) => {
                slot.classList.remove('slot-occupied');
                const team = slot.getAttribute('data-team');
                const index = parseInt(slot.getAttribute('data-index'));
                updateSlotDisplay(team, index, null);
            });

            // 重置战斗日志
            document.getElementById('battle-log').innerHTML = `
                <div class="text-center text-gray-500">战斗尚未开始</div>
                <div class="mt-4 text-left text-xs text-gray-500">
                    <p>• 组建10人红方和10人蓝方阵容后可开始战斗</p>
                    <p>• 点击"随机分配阵营"可自动分配20位英雄到双方阵营</p>
                    <p>• AI将分析双方英雄属性、战术匹配度</p>
                    <p>• 战斗采用回合制，每回合输出关键战况</p>
                    <p>• 最终根据综合战力和战术配合判定胜负</p>
                </div>
            `;

            // 禁用开始战斗按钮
            document.getElementById('start-battle').disabled = true;
            
            // 更新队伍计数
            updateTeamCounts();

            // 添加重置日志
            addBattleLog('<span class="battle-log-ai">[AI提示]</span> 游戏已重置，可重新组建阵容！');

            // 显示重置完成通知
            setTimeout(() => showNotification('游戏已重置完成！', 'success'), 500);
        }

        // 初始化事件监听
        function initEventListeners() {
            // 随机分配按钮 - 现在是唯一的队伍组建方式
            document.getElementById('random-teams').addEventListener('click', () => randomizeTeams());

            // 开始战斗按钮
            document.getElementById('start-battle').addEventListener('click', () => startBattle());

            // 重置游戏按钮
            document.getElementById('reset-game').addEventListener('click', () => resetGame());

            // 初始化所有槽位的显示（确保类别名称和英雄列表正确显示）
            document.querySelectorAll('.formation-slot').forEach(slot => {
                const team = slot.getAttribute('data-team');
                const index = parseInt(slot.getAttribute('data-index'));
                const currentHero = team === 'red' 
                    ? WarSimulation.state.redTeam[index] 
                    : WarSimulation.state.blueTeam[index];
                updateSlotDisplay(team, index, currentHero);
            });
        }

        // 显示通知提示函数
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            document.body.appendChild(notification);

            // 添加显示动画
            setTimeout(() => {
                notification.classList.add('show');
            }, 10);

            // 设置自动隐藏
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        // 启动游戏
        WarSimulation.init();

        // 显示欢迎信息
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => showNotification('欢迎来到古代英雄战争模拟！', 'success'), 1000);
        });
    </script>
</body>

</html>